package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.utils.RSAUtil;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class FileController {

    @PostMapping("getFileContent")
    public void getFileContent(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        JSONObject jsonParam = this.getJSONParam(request);
        JSONObject bizContent = (JSONObject)jsonParam.get("bizContent");
        String corpName = bizContent.get("corpName").toString();
        String date = bizContent.get("date").toString();
        String taxNo = bizContent.get("taxNo").toString();
        String idNo = bizContent.get("idNo").toString();
        String extendData = bizContent.get("extendData").toString();
        String[] fileNames = extendData.split("\\|");

        ///tax/preloan/response/当前日期/nsrsbh/
        String filePath ="/data/sftproot/cmbc/tax/preloan/response/"+date+"/"+taxNo;
        //String filePath = "G:\\民生银行\\民生银行文件服务\\加密文件";
        File allFile = new File(filePath);

        Map<String,Object> returnMap = new HashMap<>();

        Map<String,Object> headMap = new HashMap<>();

        Map<String,Object> contentMap = new HashMap<>();

        if(!allFile.exists()){
            //文件不存在
            headMap.put("returnType","E");
            headMap.put("returnCode","0001");
            headMap.put("returnMessage","没有查询到文件");
            returnMap.put("head",headMap);
            returnMap.put("bizContent",contentMap);
            response.getWriter().write(new JSONObject(returnMap).toString());
        }else{
            // 获得该文件夹内的所有文件
            File[] array = allFile.listFiles();

            if(null == array || array.length == 0){
                headMap.put("returnType","E");
                headMap.put("returnCode","0002");
                headMap.put("returnMessage","文件不全");
                returnMap.put("head",headMap);
                returnMap.put("bizContent",contentMap);
                response.getWriter().write(new JSONObject(returnMap).toString());
            }else{
                headMap.put("returnType","S");
                headMap.put("returnCode","0000");
                headMap.put("returnMessage","查询成功");
                returnMap.put("head",headMap);

                RSAUtil rsaUtil = RSAUtil.newInstance();
                //银行私钥初始化
                rsaUtil.initBankPrivateKey("/data/bank/njwjfw.pfx","123456");
                //rsaUtil.initBankPrivateKey("G:\\民生银行\\民生银行文件服务\\中国民生银行股份有限公司南京分行.pfx","123456");

                for (File file : array) {
                    String path = file.getPath();
                    String fileName = file.getName();
                    String key = fileName.split("_")[0];

                    if(null != fileNames && fileNames.length != 0){
                        for (String name : fileNames) {
                            if(key.equals(name)){
                                //根据传递得文件名称进行文件获取
                                String fileContent = RSAUtil.readTxtFile(path, "utf-8");
                                String contentResult = handleFile(fileContent);
                                Document document = DocumentHelper.parseText(contentResult);
                                Element root = document.getRootElement();
                                List<Element> childElements = root.elements();
                                Map<String,Object> childMaps = new HashMap<>();
                                handleChild(childMaps,childElements);

                                contentMap.put(key,childMaps);
                            }
                        }
                    }
                }
                returnMap.put("bizContent",contentMap);
                response.getWriter().write(new JSONObject(returnMap).toString());
            }
        }
    }

    public JSONObject getJSONParam(HttpServletRequest request){
        JSONObject jsonParam = null;
        try {
            // 获取输入流
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));

            // 写入数据到Stringbuilder
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = streamReader.readLine()) != null) {
                sb.append(line);
            }
            jsonParam = JSONObject.parseObject(sb.toString());
            // 直接将json信息打印出来
            System.out.println(jsonParam.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonParam;
    }

    /*@PostMapping("getFileContent1")
    public Map<String,Object> getFileContent1(@RequestParam String corpName,@RequestParam String date,@RequestParam String idNo,@RequestParam String taxNo,@RequestParam String extendData) throws Exception {

        ///tax/preloan/response/当前日期/nsrsbh/
        String filePath ="/data/sftproot/cmbc/tax/preloan/response/"+date+"/"+taxNo;
        //String filePath = "G:\\民生银行\\民生银行文件服务\\加密文件";
        File allFile = new File(filePath);
        // 获得该文件夹内的所有文件
        File[] array = allFile.listFiles();

        Map<String,Object> returnMap = new HashMap<>();

        Map<String,Object> headMap = new HashMap<>();

        Map<String,Object> contentMap = new HashMap<>();

        if(null == allFile || array.length == 0){
            headMap.put("returnType","E");
            headMap.put("returnCode","0002");
            headMap.put("returnMessage","文件不全");
            returnMap.put("head",headMap);
            return returnMap;
        }else{
            headMap.put("returnType","S");
            headMap.put("returnCode","0000");
            headMap.put("returnMessage","查询成功");
            returnMap.put("head",headMap);
        }


        RSAUtil rsaUtil = RSAUtil.newInstance();
        //银行私钥初始化
        rsaUtil.initBankPrivateKey("/data/bank/njwjfw.pfx","123456");
        //rsaUtil.initBankPrivateKey("G:\\民生银行\\民生银行文件服务\\中国民生银行股份有限公司南京分行.pfx","123456");

        for (File file : array) {
            String path = file.getPath();
            String fileName = file.getName();
            String key = fileName.split("_")[0];

            String fileContent = RSAUtil.readTxtFile(path, "utf-8");
            String contentResult = handleFile(fileContent);
            Document document = DocumentHelper.parseText(contentResult);
            Element root = document.getRootElement();
            List<Element> childElements = root.elements();
            Map<String,Object> childMaps = new HashMap<>();
            handleChild(childMaps,childElements);

            contentMap.put(key,childMaps);

        }
        returnMap.put("bizContent",contentMap);
        return returnMap;
    }
*/
    private void handleChild(Map<String, Object> childMaps, List<Element> childElements) {

        for (Element childElement : childElements) {

            String name = childElement.getName();

            //有子集，继续处理子集

            List<Element> elements = childElement.elements();

            if(null != elements && elements.size() != 0){

                Map<String,Object> childMap = new HashMap<>();
                handleChild(childMap,elements);
                if(childMaps.containsKey(name)){
                    Object o = childMaps.get(name);
                    Class<?> aClass = o.getClass();

                    if("java.util.HashMap".equals(aClass.getName())){
                        Map<String,Object> map = (Map<String,Object>)childMaps.get(name);
                        List<Map<String,Object>> list = new ArrayList<>();
                        list.add(map);
                        list.add(childMap);
                        childMaps.put(name,list);
                    }else{
                        List<Map<String,Object>> list = (List<Map<String,Object>>)childMaps.get(name);
                        list.add(childMap);
                        childMaps.put(name,list);
                    }
                }else{
                    childMaps.put(name,childMap);
                }
            }else{
                String text = childElement.getText();
                childMaps.put(name,text);
            }
        }
    }

    public String handleFile(String mytext) throws Exception {

        return RSAUtil.rsaDecrypt(RSAUtil.getPrivateBankKey(),mytext);
    }

}